<template>
  <div>
    <!-- 父传子 -->
    <MyTable :list="list">
      <!-- 具名插槽 -->
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
   <!-- scope: {row: obj}  本应该是 scope 咱们使用的是scope里面的row 所以解构出来-->
      <template #body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
            v-fff
            v-model="row.inputValue"
            @blur="row.inputVisible = false"
            @keydown.enter="enterFn(row)"
            @keydown.esc="row.inputValue = ''"
          />
          <!-- 使用v-if  v-else 来控制input跟button切换  关联的是row.inputVisible -->
          <!-- v-fff 自定义指令传值 绑定谁传入的就是谁  -->
          <!-- v-model="row.inputValue" 关联的输入的值 -->
          <!-- 定义键盘事件来实现所要的功能 -->
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="row.inputVisible = true"
          >
            +Tag
          </button>

          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge badge-warning"
          >
            {{ item }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delFn(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable";
// 引用axios
import axios from "axios";
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [], // 所有数据
    };
  },
  // 请求数据
  created() {
    axios({
      url: "/api/goods",
    })
      .then((res) => (this.list = res.data.data))
      .catch((err) => console.log(err));
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    enterFn(row) {
      if (row.inputValue.trim().length === 0) {
        alert("输入有误");
        return;
      }
      row.tags.push(row.inputValue);
      row.inputValue = "";
    },
  },
  // 绑定谁传入的就是谁
  directives: {
    fff: {
      inserted(el) {
        el.focus();
      },
    },
  },
};
</script>